<template>
  <el-dialog
    :title="title"
    :visible.sync="visible"
    :before-close="closeDialog"
    :close-on-click-modal="false"
    width="30%"
  >
    <el-form
      ref="connectionStringForm"
      v-loading="loading"
      label-position="top"
      :model="form"
    >
      <el-form-item prop="isDefaultConnectionString">
        <el-checkbox v-model="isDefaultConnectionString" :label="$t('AbpTenantManagement[\'DisplayName:UseSharedDatabase\']')" name="type" />
      </el-form-item>
      <el-form-item v-show="!isDefaultConnectionString" :label="$t('AbpTenantManagement[\'DisplayName:DefaultConnectionString\']')" prop="defaultConnectionString">
        <el-input v-model="form.defaultConnectionString" />
      </el-form-item>
      <!-- 隐藏表单 -->
      <el-form-item prop="id" hidden>
        <el-input v-model="form.id" />
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="closeDialog">{{ $t('AbpTenantManagement[\'Cancel\']') }}</el-button>
      <el-button type="primary" @click="submitForm">
        <i class="el-icon-check" />
        {{ $t('AbpTenantManagement[\'Save\']') }}
      </el-button>
    </span>
  </el-dialog>
</template>

<script>
import {
  getDefaultConnectionString,
  editDefaultConnectionString,
  deleteDefaultConnectionString
} from '@/api/administration/tenant/tenant'
export default {
  name: 'ConnectionStrings',
  props: {
    context: {
      type: Object,
      required: true
    },
    visible: {
      type: Boolean,
      required: true,
      default: false
    }
  },
  data() {
    return {
      title: this.$t('AbpTenantManagement[\'ConnectionStrings'),
      loading: false,
      isDefaultConnectionString: true,
      form: {
        id: '',
        defaultConnectionString: ''
      }
    }
  },
  watch: {
    context(newVal, oldVal) {
      this.loading = true
      this.$nextTick(function() {
        getDefaultConnectionString(newVal.id).then(resp => {
          if (resp) {
            this.isDefaultConnectionString = false
          }
          this.form.id = newVal.id
          this.form.defaultConnectionString = resp
        })
        this.loading = false
      })
    }
  },
  methods: {
    async submitForm() {
      if (this.isDefaultConnectionString) {
        await deleteDefaultConnectionString(this.form.id)
      } else {
        await editDefaultConnectionString(this.form.id, this.form.defaultConnectionString)
      }
      this.$message({ message: this.$t('AbpTenantManagement[\'Ok\']'), type: 'success' })
      this.closeDialog()
      this.$emit('saveSucceed')
    },
    closeDialog() {
      this.resetDialog() // 重置表单
      this.$emit('update:visible', false)
    },
    resetDialog() {
      this.$refs.connectionStringForm.resetFields()
    }
  }
}
</script>

<style scoped>
</style>
